package cnm.dao.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import cnm.dao.BoardDAO;
import cnm.model.Board;

import java.util.List;

public class BoardHibernateDAO extends GenericHibernateDAO<Board> implements BoardDAO
{
	public BoardHibernateDAO()
	{
		super(Board.class);
	}

	public Long getCount()
	{
		return (Long) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("select count(*) from Board p");							
				return query.uniqueResult();
			}
		}, true);
	}	
	
	public Long getCountByKeyword(final String keyword)
	{
		return (Long) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				String queryStr = "select count(*) from Board p where" +
					" p.boardName like :name or p.boardDesc like :desc";
				Query query = session.createQuery(queryStr)
						.setString("name", "%"+keyword+"%")
						.setString("desc", "%"+keyword+"%");		
				return query.uniqueResult();
			}
		}, true);
	}	
		
	@SuppressWarnings("unchecked")
	public List<Board> findByKeyword(final String keyword, final int firstResult, final int maxResults)
	{
		return (List<Board>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				String queryStr = "from Board p " +
						"where p.boardName like :name or " +
						"p.boardDesc like :desc " +
						"order by p.boardId desc";
				Query query = session.createQuery(queryStr)
						.setString("name", "%"+keyword+"%")
						.setString("desc", "%"+keyword+"%");
				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);	
				return query.list();
			}
		}, true);
	}	
		
	public Board getLatestBoard(final int type) {
		return (Board) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				String queryStr = "from Board p " +
						"where p.boardType = :type order by p.boardId desc";
				Query query = session.createQuery(queryStr)
						.setInteger("type", type);
				query.setFirstResult(0);
				query.setMaxResults(1);	
				return query.uniqueResult();
			}
		}, true);		
	}
	
}
